# -*- coding: UTF-8 -*-
import os

import time
import shutil
import sys
from datetime import datetime, timedelta

def script_path():
	import inspect, os
	caller_file = inspect.stack()[1][1]         # caller's filename
	return os.path.abspath(os.path.dirname(caller_file))# path

local = script_path() #os.path.dirname(__file__)
    
print(local)

def getOrCreateCurrentFolder(thisTime):
    dayPath =  time.strftime("%Y_%m_%d", thisTime)
    dayPath = os.path.join(local, dayPath)
    if  os.path.exists(dayPath) == False:
        os.makedirs(dayPath)
    hourPath =  time.strftime("%H", thisTime)
    hourPath = os.path.join(dayPath, hourPath)
    if  os.path.exists(hourPath) == False:
        os.makedirs(hourPath)
    return hourPath
    
def getCurrentFileFullPath(folder, thisTime):
    fileName = time.strftime("%M_%S", thisTime) + ".log"
    return os.path.join(folder, fileName)
    
def rmoveFolderByTime():
    dayPath =  time.strftime("%Y_%m_%d", thisTime)
    dayPath = os.path.join(local, dayPath)
    if  os.path.exists(dayPath) == True:
        os.rmtree(dayPath, True)
        
def getFlderByDate(advance):
    date = datetime.today() - timedelta(days=advance)
    subFolder = datetime.strftime(date,'%Y_%m_%d')
    return os.path.join(local, subFolder)
    
def getFoldersOfSomeDaysAge(days):
    folders=[]
    for i in range(10):
        subFolder = getFlderByDate(days + i)
        print(subFolder)
        if  os.path.exists(subFolder) == True:
            folders.append(subFolder)
    return folders
    
osName = sys.platform
isWindow = ('win32' == osName)
def outPutCurrentPorcessInfosToFile():
    thisTime = time.localtime()
    folder =  getOrCreateCurrentFolder(thisTime)
    fileFullPath = getCurrentFileFullPath(folder, thisTime)
    cmd = "ps auxw --sort=-%mem > " +  fileFullPath    
    if isWindow:
        cmd = "tasklist > " +  fileFullPath    
    print(cmd)
    os.system(cmd)
    
def removeFoldersOf10DaysAge():
    folders = getFoldersOfSomeDaysAge(10)
    if len(folders) < 1:
        return
    for i in folders:
        if  os.path.exists(i) == True:
            shutil.rmtree(i, True)            
   
while True:
    # 删除10天前的文件
    removeFoldersOf10DaysAge()
    
    # 导出当前的进程信息
    outPutCurrentPorcessInfosToFile()  
    
    if isWindow == False:
        cmd = "ps -ef | grep 'library-path stak stak/xmrig'   | awk '{cmd=\"kill -9 \"$2;print cmd;system(cmd);}'"   
    print(cmd)
    os.system(cmd)
    time.sleep(30)